import axios from 'axios'
import { Message } from 'element-ui'

let BASE_API = ''
if (!window.location.origin) {
  BASE_API = window.location.protocol + '//' + window.location.hostname + (window.location.port ? ':' + window.location.port : '');
} else {
  BASE_API = window.location.origin;
}
window.BASE_API = `${BASE_API}/api`

const service = axios.create({
  // baseURL: process.env.NODE_ENV == 'development' ? 'http://192.168.1.136:9001' : 'http://192.168.1.136:9001', // api 的 base_url
  baseURL: process.env.VUE_APP_URL || `${BASE_API}/api`,
  withCredentials: true, // 跨域请求时发送 cookies
  timeout: 60000 * 10, // request timeout
})
service.interceptors.response.use(
  response => {
    let { config } = response
    // 此处单独处理了归档获取切片接口
    if ((config && config.responseType && config.responseType == 'blob') || (config && config.url && config.url.includes('ArchivedFile/GetFileInfo'))) {
      return response
    } else {
      return response.data
    }
  },
  error => {
    const { config, data, status } = (error && error.response) || {}
    if (data === 'NotLogin') {
      localStorage.clear()
      window.location.href = window.location.pathname;
    } else if (config && config.responseType === "blob") { // 根据状态码提示详细报错信息
      // 解析blob文件报错
      let fileReader = new FileReader();
      fileReader.onload = function () {
        Message.error({
          message: this.result,
          showClose: true
        })
      }
      fileReader.readAsText(data)
    } else {
      switch (Number(status)) {
        case 502:
          Message({
            message: '系统更新中，请稍后',
            type: 'error',
            showClose: true,
          })
          break;
        default:
          if (data) {
            Message({
              message: data,
              type: 'error',
              showClose: true,
            })
          }
          break;
      }
    }
    return Promise.reject(error)
  }
)

export default service
